package org.cweili.vehicle.service.driver

import org.cweili.vehicle.entity.Expense
import org.cweili.vehicle.service.BaseService
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.cweili.vehicle.util.Utils
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

import com.alibaba.fastjson.JSONArray

/**
 * 司机费用服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:26:29
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class DriverExpenseService extends BaseService {

	Page<Expense> getList(String json) {
		def obj = JSON.parseObject(json)

		def verifyStatus = JSON.getByte(obj, "verifyStatus")
		def page = JSON.getInteger(obj, "page")

		return expenseRepository.findByCommitCustomerAndVerifyStatus(getCustomer(), verifyStatus,
		new PageRequest(page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"))
	}

	boolean del(String json) {
		try {
			def array = JSONArray.parseArray(json)

			for (obj in array) {
				int id = Utils.parseInt(obj)
				if (1 > id) {
					return false
				}
				def expense = expenseRepository.findOne(id)
				if (expense) {
					if (Expense.VERIFY_PASSED > expense.getVerifyStatus()) {
						vehicleRepository.delete(id)
					}
				}
			}
		} catch (Exception e) {
			log.error(e + json, e)
			return false
		}
		return true
	}

	boolean save(String json) {
		def obj = JSON.parseObject(json)

		def classification = JSON.getByte(obj, "classification")
		def id = JSON.getInteger(obj, "id")
		def vehicleLicensePlate = JSON.getString(obj, "vehicleLicensePlate")
		def remark = JSON.getString(obj, "remark")
		def priceString = JSON.getString(obj, "price")

		if (Utils.isEmpty(vehicleLicensePlate)) {
			return false
		}

		def expense
		if (id > 0) {
			expense = expenseRepository.findOne(id)
			if (!expense) {
				return false
			} else if (Expense.VERIFY_PASSED <= expense.getVerifyStatus()) {
				return false
			}
		} else {
			expense = new Expense()
			expense.commitCustomer = getCustomer()
		}

		def vehicle = vehicleRepository.findByLicensePlate(vehicleLicensePlate)
		if (!vehicle) {
			return false
		}

		expense.classification = classification
		expense.commitDate = new Date()
		expense.remark = remark
		expense.price = Utils.stringToMoney(priceString)
		expense.vehicle = vehicle
		expense.commitDate = new Date()
		expense.verifyStatus = Expense.VERIFY_UNVERIFYED

		return expenseRepository.save(expense)
	}
}
